<template>
  <div>
    <myDivider :name="type == 'add' ? '新增合同' : '修改合同'"></myDivider>
    <el-page-header @back="$router.back(-1)">
    </el-page-header>
    <el-form style="width: 600px;margin-top: 50px;" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px"
      class="demo-ruleForm">
      <el-form-item label="关联小区：" prop="residentialId">
        <el-select style="width: 520px;" ref="residentialSelect" v-model="ruleForm.residentialId" placeholder="请选择小区"
          @change="residentialChange">
          <el-option v-for="item, i in residentialData" :key="i" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <div style="display: flex;">
        <el-form-item label="合同名称：" prop="name">
          <el-input style="width: 200px;" maxlength="30" v-model="ruleForm.name" placeholder="请输入合同名称"></el-input>
        </el-form-item>
        <el-form-item label="合同类别：" prop="category">
          <el-select style="width: 200px;" v-model="ruleForm.category" placeholder="请选择合同类别" @change="HZLBchange">
            <el-option label="外包合作合同" value="1"></el-option>
            <el-option label="物业服务合同" value="2"></el-option>
            <el-option label="装修监管合同" value="3"></el-option>
            <el-option label="房屋租售合同" value="4"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div style="display: flex;">
        <el-form-item v-if="type == 'update'" label="合同编号：">
          <el-input disabled style="width: 200px;" v-model="ruleForm.contractNumber" placeholder="自动生成"></el-input>
        </el-form-item>
        <el-form-item label="丙方名称：" prop="partyC">
          <el-input style="width: 200px;" maxlength="20" v-model="ruleForm.partyC" placeholder="请输入丙方名称"></el-input>
        </el-form-item>

      </div>
      <div style="display: flex;">
        <el-form-item label="甲方名称：" prop="partyA">
          <el-input style="width: 200px;" maxlength="20" v-model="ruleForm.partyA" placeholder="请输入甲方名称"></el-input>
        </el-form-item>
        <el-form-item label="乙方名称：" prop="partyB">
          <el-input style="width: 200px;" maxlength="20" v-model="ruleForm.partyB" placeholder="请输入乙方名称"></el-input>
        </el-form-item>
      </div>

      <div style="display: flex;">
        <el-form-item label="金额：" prop="amountPrice">
          <div style="display: flex;width: 200px;">
            <el-input type="number" style="width: 140px;" v-model="ruleForm.amountPrice" placeholder="请输入金额"></el-input>
            <span style="margin-left: 15px;">元</span>
          </div>
        </el-form-item>
        <el-form-item label="签订日期：" prop="signingDate">
          <el-date-picker style="width: 200px;" v-model="ruleForm.signingDate" type="date" placeholder="选择日期"
            value-format="yyyy.MM.dd">
          </el-date-picker>
        </el-form-item>
      </div>
      <el-form-item label="内容概要：" prop="description">
        <el-input style="width: 520px;" v-model="ruleForm.description" type="textarea" :rows="5" maxlength="200"
          show-word-limit placeholder="请输入会议概要，不超过200字"></el-input>
      </el-form-item>
      <el-form-item label="图片：" prop="" required>
        <MyUploadImgNotDetele :id="UploadId" v-if="ImgFileShow" :EchoImgList="EchoImgList" @getImgList="getImgList"
           @deleteImgList="deleteImgList"
          uploadUrl="/business/contract/uploadImg"></MyUploadImgNotDetele>
      </el-form-item>
      <el-form-item label="附件：">
        <MyUploadFileNotDetele :id="UploadId" v-if="ImgFileShow" :EchoFileList="EchoFileList" @getFileList="getFileList"
          @deleteFileList="deleteFileList" uploadUrl="/business/contract/uploadAnnex">
        </MyUploadFileNotDetele>
      </el-form-item>
      <el-form-item label="经办人：" prop="userName">
        <el-input style="width: 200px;" v-model="ruleForm.userName" placeholder="自动匹配" disabled></el-input>
      </el-form-item>

      <el-form-item class="btn">
        <el-button style="width: 100px;" type="primary" @click="submitForm('ruleForm')">{{ type == 'add' ?
      '新增' : '修改' }}</el-button>
        <el-button style="width: 100px;" type="info" @click="goBack('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import MyUploadFileNotDetele from '../../components/upload/MyUploadFileNotDetele';
import MyUploadImgNotDetele from '../../components/upload/MyUploadImgNotDetele';
export default {
  components: {
    MyUploadFileNotDetele,
    MyUploadImgNotDetele
  },
  data() {
    return {
      type: '',//新增还是详情
      keyAddress: '',
      ruleForm: {},
      rules: {
        residentialId: [
          { required: true, message: '请选择关联小区', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入合同名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择合同类别', trigger: 'change' }
        ],
        amountPrice: [
          { required: false, },
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的格式,可保留两位小数' }
        ],
        partyC: [
          { required: false, message: '请输入丙方名称', trigger: 'blur' }
        ],
        partyA: [
          { required: true, message: '请输入甲方名称', trigger: 'blur' }
        ],
        partyB: [
          { required: true, message: '请输入乙方名称', trigger: 'blur' }
        ],
        signingDate: [
          { required: true, message: '请选择签订日期', trigger: 'change' }
        ],
        userName: [
          { required: true, message: '请输入经办人', trigger: 'blur' }
        ],
      },
      ImgFileShow: false,//修改的时候，图片和文件需要在数据获取到之后再加载
      EchoImgList: [],
      EchoFileList: [],
      UploadId: 0,

      residentialData: [],
      logOnUser: {},
      deleteImg: [],
      deleteFile: [],
    };
  },
  async activated() {
    this.type = this.$route.query.type //新增？修改？
    this.resetForm() //清空内容
    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.ImgFileShow = false //隐藏图片附件

    this.EchoImgList = [] //回显设为空
    this.EchoFileList = []//回显设为空
    this.deleteImg = []
    this.deleteFile = []

    this.$set(this.ruleForm, 'userName', this.logOnUser.name)
    this.getResidentialData() //获取小区列表

    switch (this.type) {
      case 'add': //新增  新增  新增  新增  新增
        this.UploadId = 0
        setTimeout(() => {
          this.ImgFileShow = true
        }, 100)

        break

      case 'update'://修改   修改   修改   修改   修改   修改
        let res = await this.$api.contract.getContractDetail(this.$route.query.id)
        this.ruleForm = res.data
        this.UploadId = res.data.id
        if (res.data.annexPathArr == null) res.data.annexPathArr = [] //附件数组返回的空，转换为数组
        this.EchoImgList = res.data.imgs //图片数组回显
        this.EchoFileList = res.data.annexPathArr //文件数组回显
        console.log(res.data, '详情数据');
        this.$set(this.ruleForm, 'userName', res.data.createUserName) //经办人回显
        setTimeout(() => {
          this.ImgFileShow = true
        }, 100)

        break
    }

    this.$nextTick(() => { //清除验证
      this.$refs['ruleForm'].clearValidate()
    })
  },

  methods: {
    deleteImgList(val) {
      this.deleteImg.push(val)
    },
    deleteFileList(val) {
      this.deleteFile.push(val)
    },
    resetForm() { //清空内容

      this.$set(this.ruleForm, 'residentialId', '')
      this.$set(this.ruleForm, 'residentialName', '')
      this.$set(this.ruleForm, 'name', '')
      this.$set(this.ruleForm, 'category', '')
      this.$set(this.ruleForm, 'contractNumber', '')
      this.$set(this.ruleForm, 'partyC', '')
      this.$set(this.ruleForm, 'partyA', '')
      this.$set(this.ruleForm, 'partyB', '')
      this.$set(this.ruleForm, 'amountPrice', '')
      this.$set(this.ruleForm, 'signingDate', '')
      this.$set(this.ruleForm, 'description', '')
      this.$set(this.ruleForm, 'userName', '')
      this.$set(this.ruleForm, 'imgs', [])
      this.$set(this.ruleForm, 'annexPathArr', [])
    },
    async getResidentialData() {

      let res = await this.$api.contract.myGetCommunityList({
        "unitType": this.logOnUser.unitType, //匹配当前登录人单位  机关agency 机构company 系统system
        "unitId": this.logOnUser.unitId //系统传0
      })
      if (res.code == 200) {
        this.residentialData = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    submitForm(formName) { //提交按钮

      switch (this.type) {
        case 'add':
          let userData = JSON.parse(sessionStorage.getItem('logOnUser'))
          this.$set(this.ruleForm, 'unitType', userData.unitType)
          this.$set(this.ruleForm, 'unitId', userData.unitId)
          this.$refs[formName].validate(async (valid) => {
            if (valid) {
              if (this.ruleForm.annexPathArr == undefined) { //如果没选附件
                this.ruleForm.annexPathArr = []
              }
              if (this.ruleForm.imgs == undefined || this.ruleForm.imgs.length < 1) { //如果图片为空或者图片数量为0
                this.$message.error('请上传图片')
                return
              }
              this.$confirm('是否提交?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(async () => {

                //删除图片和附件
                this.deleteImg.forEach(async el => {
                  let res = await this.$api.ImgFile.delete(defaultUrl+'/business/contract/deleteImg', {
                    "picName": el
                  })
                })
                this.deleteFile.forEach(async el => {
                  let res = await this.$api.ImgFile.delete(defaultUrl+'/business/contract/deleteAnnex', {
                    "filename": el
                  })
        
                })
                let {
                  unitType, unitId, residentialId,
                  residentialName, name, category,
                  partyA, partyB, partyC, amountPrice,
                  signingDate, description, imgs, annexPathArr } = this.ruleForm
                let params = {
                  unitType, unitId, residentialId,
                  residentialName, name, category,
                  partyA, partyB, partyC, amountPrice,
                  signingDate, description, imgs, annexPathArr
                }
                let res = await this.$api.contract.insertContract(params)
                console.log(res, '返回的结果');
                if (res.code == 200) {
                  this.$message({
                    message: '新增成功',
                    type: 'success'
                  });
                  this.$router.back(-1)
                } else {
                  this.$message.error('新增失败，请联系管理员');
                }
              }).catch(() => {

              });

            } else {
              console.log('error submit!!');
              return false;
            }
          });
          break
        case 'update':
          this.$refs[formName].validate(async (valid) => {
            if (valid) {
              if (this.ruleForm.annexPathArr == undefined) { //如果没选附件
                this.ruleForm.annexPathArr = []
              }
              if (this.ruleForm.imgs == undefined || this.ruleForm.imgs.length < 1) { //如果图片为空或者图片数量为0
                this.$message.error('请上传图片')
                return
              }
              this.$confirm('是否修改?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(async () => {
                   //删除图片和附件
                   this.deleteImg.forEach(async el => {
                  let res = await this.$api.ImgFile.delete(defaultUrl+'/business/contract/deleteImg', {
                    "picName": el
                  })
                })
                this.deleteFile.forEach(async el => {
                  let res = await this.$api.ImgFile.delete(defaultUrl+'/business/contract/deleteAnnex', {
                    "filename": el
                  })
        
                })
             
                let {
                  unitType, unitId, residentialId,
                  residentialName, name, category,
                  partyA, partyB, partyC, amountPrice,
                  signingDate, description, imgs, annexPathArr, id } = this.ruleForm
                let params = {
                  unitType, unitId, residentialId,
                  residentialName, name, category,
                  partyA, partyB, partyC, amountPrice,
                  signingDate, description, imgs, annexPathArr, id
                }
                let res = await this.$api.contract.updateContract(params)
                if (res.code == 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                  this.$router.back(-1)
                } else {
                  this.$message.error('新增失败，请联系管理员');
                }
              }).catch(() => {

              });

            } else {
              console.log('error submit!!');
              return false;
            }
          });
          break
      }

    },
    goBack(formName) { //取消按钮
      this.$router.back(-1)
    },
    residentialChange() { //所选小区切换事件
      this.$nextTick(() => {
        this.$set(this.ruleForm, 'residentialName', this.$refs.residentialSelect.selectedLabel)
      })

    },
    HZLBchange(e) { //合作类别更新事件
      switch (e) {
        case '1':
        case '2':
          this.rules.partyC[0].required = false
          break
        case '3':
        case '4':
          this.rules.partyC[0].required = true
          break
      }
      this.$nextTick(() => { //清除验证
        this.$refs['ruleForm'].clearValidate()
      })
    },






    getImgList(val) {
      this.$set(this.ruleForm, 'imgs', val)
    },
    getFileList(val) {
      this.$set(this.ruleForm, 'annexPathArr', val)
    },
  }
}
</script>
<style lang="less" scoped>
.btn {
  position: fixed;
  bottom: 10px;
  right: 70px;
}

.mapStyle {
  height: 185px;
  width: 1070px;
  margin-left: 100px;
  position: relative;
  margin-bottom: 100px;

  #container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 100%;

  }

  .keyAddressStyle {
    position: absolute;
    right: 15px;
    top: 15px;
    width: 250px;
    height: 30px;
  }
}
</style>